package jimmy.com.client.helper;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.jimmy.common.util.SharedUtils;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import jimmy.com.client.ClientApp;
import jimmy.com.client.config.SharedKey;

/**
 * Created by Jimmy on 2017/7/6 0006.
 */
public class JPushHelper {

    private static JPushHelper instance;

    public synchronized static JPushHelper newInstance() {
        if (instance == null) {
            instance = new JPushHelper();
        }
        return instance;
    }

    private static final int MSG_SET_ALIAS = 1001;

    private boolean isSetting = false;

    private final Handler mJPushHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAliasAndTags(ClientApp.context, (String) msg.obj, null, mAliasCallback);
                    break;
                default:
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0:
                    SharedUtils.putString(ClientApp.context, SharedKey.JPUSH_ALISA, alias);
                    break;
                case 6002:
                    mJPushHandler.sendMessageDelayed(mJPushHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    break;
            }
        }
    };

    public void bindJPushAlisa(String alias) {
        if (!isSetting && !TextUtils.equals(SharedUtils.getString(ClientApp.context, SharedKey.JPUSH_ALISA), alias)) {
            isSetting = true;
            mJPushHandler.sendMessage(mJPushHandler.obtainMessage(MSG_SET_ALIAS, alias));
        }
    }

}
